package handler

import (
	"context"
	"gitee.com/DevilYyx/common"
	"gitee.com/DevilYyx/pod/domain/model"
	"gitee.com/DevilYyx/pod/domain/service"
	"gitee.com/DevilYyx/pod/proto/pod"
	"strconv"
)

type PodHandler struct {
	service service.IPodService
}

func NewPodHandler(podService service.IPodService) *PodHandler {
	return &PodHandler{service: podService}
}

func (p *PodHandler) AddPod(ctx context.Context, podInfo *pod.PodInfo, response *pod.Response) error {
	podId, err := p.service.CreateToK8s(podInfo)
	if err != nil {
		common.Error(err)
		response.Msg = err.Error()
		return err
	} else {
		msg := "Pod" + strconv.FormatInt(podId, 10) + "添加成功"
		common.Info(msg)
	}
	return nil
}

func (p *PodHandler) DeletePod(ctx context.Context, id *pod.PodId, response *pod.Response) error {
	podModel, err := p.service.FindPodByID(id.Id)
	if err != nil {
		common.Error(err)
		response.Msg = err.Error()
		return err
	}
	err = p.service.DeleteFromK8s(podModel)
	if err != nil {
		common.Error(err)
		response.Msg = err.Error()
		return err
	}
	return err
}

func (p *PodHandler) FindPodByID(ctx context.Context, id *pod.PodId, info *pod.PodInfo) error {
	podModel, err := p.service.FindPodByID(id.Id)
	if err != nil {
		common.Error(err)
		return err
	}
	err = common.SwapTo(podModel, info)
	if err != nil {
		common.Error(err)
		return err
	}
	return nil
}

func (p *PodHandler) UpdatePod(ctx context.Context, pod *pod.PodInfo, response *pod.Response) error {
	podModel := &model.Pod{}
	err := common.SwapTo(pod, podModel)
	if err != nil {
		common.Error(err)
		response.Msg = err.Error()
		return err
	}
	err = p.service.UpdatePod(podModel)
	if err != nil {
		common.Error(err)
		response.Msg = err.Error()
		return err
	}
	return nil
}

func (p *PodHandler) FindAllPod(ctx context.Context, args *pod.FindAll, resp *pod.AllPod) error {
	pods, err := p.service.FindAllPod()
	if err != nil {
		common.Error(err)
		return err
	}
	for _, v := range pods {
		podInfo := &pod.PodInfo{}
		err = common.SwapTo(v, podInfo)
		if err != nil {
			common.Error(err)
			return err
		}
		resp.PodInfo = append(resp.PodInfo)
	}
	return nil
}
